Easy2Siksha.com
GNDU Question Paper-2025
Bachelor of Computer Application (BCA) (Hons.)
1
st
Sem. (Batch 2024-28) (CBGS)
INTRODUCTION TO C PROGRAMMING
Time Allowed: Three Hours Max. Marks: 75
Note: Attempt Five questions in all, selecting at least One question from each section. The
Fifth question may be attempted from any section. All questions carry equal marks.
SECTION-A
1. What is the use of Algorithm. Flowchart, and Program? Which symbols are used in a flowchart?
2. Explain the meaning and use of the following in C
(a) Token
(b) #define
(c) typedef
(d) enum.
SECTION-B
Write a program in C to get a number from the user and calculate the sum of all its digits which are
even.
4. What is a storage class? Explain different storage classes available in C. Give an example of
each.
SECTION-C
5. What are the different ways to pass arguments to a function in C? Give an example of each.
Easy2Siksha.com
6. What is a pointer? What are the various uses of pointers?
Give an example of passing an array to a function.
SECTION-D
7 What are user-defined data types in C? How can you create a structure and union in C? Give
differences between both.
8 Write and explain various file handling functions available in C.
GNDU Answer Paper-2025
Bachelor of Computer Application (BCA) (Hons.)
1
st
Sem. (Batch 2024-28) (CBGS)
INTRODUCTION TO C PROGRAMMING
Time Allowed: Three Hours Max. Marks: 75
Note: Attempt Five questions in all, selecting at least One question from each section. The
Fifth question may be attempted from any section. All questions carry equal marks.
SECTION-A
1. What is the use of Algorithm. Flowchart, and Program? Which symbols are used in a
flowchart?
Ans: When we use a computer, we usually see only the final result on the screen. For
example, when we calculate marks, play a game, or search something online, the computer
gives the answer very quickly. But behind every task, there is a proper step-by-step process.
This process is built with the help of Algorithms, Flowcharts, and Programs. These three are
very important in computer programming because they help a programmer solve problems
in an organized and easy way.
1. Algorithm
Easy2Siksha.com
An Algorithm is a step-by-step method used to solve a problem or complete a task.
In simple words, an algorithm is like a recipe for cooking food. When we cook noodles, we
follow steps like:
1. Boil water
2. Add noodles
3. Add masala
4. Cook for 2 minutes
5. Serve hot
Similarly, in computers, we give instructions step by step so that the computer can solve the
problem correctly.
Use of Algorithm
Algorithms are used because they:
Help solve problems in a systematic way
Make programming easier
Save time and reduce confusion
Help find mistakes before writing the actual program
Improve the efficiency of a solution
For example, if we want to calculate the sum of two numbers, the algorithm can be:
Algorithm to Add Two Numbers
1. Start
2. Take two numbers A and B
3. Add A + B
4. Store result in C
5. Display C
6. Stop
This is a simple algorithm. It clearly explains what to do step by step.
Advantages of Algorithm
Easy to understand
Easy to modify
Helps in planning
Can be used in any programming language
However, algorithms are written in simple language, so computers cannot directly
understand them. That is why we need programs.
Easy2Siksha.com
2. Flowchart
A Flowchart is a graphical or pictorial representation of an algorithm.
Instead of writing steps only in words, a flowchart uses symbols and arrows to show the
flow of work. It makes the solution more visual and easier to understand.
A flowchart is very useful because sometimes diagrams explain things better than long
paragraphs.
Use of Flowchart
Flowcharts are used to:
Understand the logic of a problem easily
Show the sequence of steps visually
Find errors quickly
Improve communication between programmers
Make complex problems simple
For example, a teacher explaining a process with diagrams is easier to understand than only
speaking. In the same way, flowcharts help programmers.
Symbols Used in a Flowchart
Different symbols are used in a flowchart, and each symbol has a special meaning.
1. Start/Stop Symbol (Oval Shape)
This symbol shows the beginning or ending of a process.
Diagram:
_________
/ \
| START |
\_________/
or
_________
/ \
| STOP |
\_________/
2. Process Symbol (Rectangle)
Easy2Siksha.com
This symbol represents a process or instruction.
Example:
Add two numbers
Diagram:
_____________
| Add A + B |
|_____________|
3. Input/Output Symbol (Parallelogram)
This symbol is used for taking input or showing output.
Example:
Enter number or Display result
Diagram:
____________
/ Enter A,B /
/____________/
4. Decision Symbol (Diamond Shape)
This symbol is used when a decision has to be made, such as Yes/No or True/False.
Example:
Is number greater than 0?
Diagram:
/\
/ \
/Yes \
\ No /
\ /
\/
5. Arrow Symbol
Arrows show the direction or flow of steps.
Easy2Siksha.com
Diagram:
-------->
Example of a Simple Flowchart
Let us make a simple flowchart for adding two numbers.
START
|
v
Enter A,B
|
v
C = A + B
|
v
Display C
|
v
STOP
This flowchart clearly explains the process visually.
3. Program
A Program is a set of instructions written in a programming language that the computer can
understand and execute.
While algorithms and flowcharts are mainly for planning and understanding, a program is
the actual code written for the computer.
Programs are written in languages like:
C
C++
Java
Python
Use of Program
Programs are used to:
Perform tasks on a computer
Solve real-world problems
Automate work
Easy2Siksha.com
Create software, apps, and games
For example, calculators, mobile apps, websites, and games all work using programs.
Relationship Between Algorithm, Flowchart, and Program
These three concepts are connected with each other.
Step 1: Algorithm
First, we think about the solution step by step.
Step 2: Flowchart
Then, we draw the steps using symbols.
Step 3: Program
Finally, we write the actual code in a programming language.
So the process becomes:
Problem → Algorithm → Flowchart → Program → Output
Real-Life Example
Suppose you want to withdraw money from an ATM.
Algorithm
1. Insert ATM card
2. Enter PIN
3. Select amount
4. Withdraw money
5. Collect receipt
Flowchart
The same process can be shown using symbols and arrows.
Program
The ATM machine software is written as a program using programming languages.
This example shows how algorithms, flowcharts, and programs work together in real life.
Easy2Siksha.com
Conclusion
Algorithms, flowcharts, and programs are the basic foundation of computer programming.
An algorithm provides step-by-step instructions to solve a problem. A flowchart represents
those steps visually using symbols and arrows. A program converts the solution into a
language that the computer can understand and execute.
These tools make problem-solving easier, more organized, and more efficient. Without
them, writing computer programs would become confusing and difficult. Therefore, every
programmer first learns how to create algorithms and flowcharts before writing programs.
2. Explain the meaning and use of the following in C
(a) Token
(b) #define
(c) typedef
(d) enum.
Ans: Learning C programming can sometimes feel like you’ve been dropped into an alien
civilization. The syntax looks cryptic, the rules are incredibly strict, and the compiler acts like
an unforgiving grammar teacher who yells at you for forgetting a single semicolon. But
underneath that rigid exterior, C is actually a beautifully logical language. It gives you, the
programmer, absolute control over the computer’s brain.
To really understand C, it helps to think of programming not as typing math equations, but
as directing a massive construction project. You are the architect, and the C compiler is your
foreman. To communicate effectively with your foreman, you need to understand the basic
vocabulary and the special tools at your disposal.
Today, we are going to look closely at four fascinating concepts that help you build your
software house: Tokens, #define, typedef, and enum. We will unpack exactly what they
mean, how you use them, and why they make your life as a coder infinitely easier.
1. Token: The Atoms of Your Code
Imagine you are reading a book. How does your brain process the story? You don't look at
the entire page as one giant blur of ink. Instead, your brain breaks the page down into
sentences, and those sentences into individual words and punctuation marks.
In the world of C programming, a token is the smallest individual unit of code that the
compiler can understand. Just like a word is the smallest meaningful unit of a sentence, a
token is the smallest meaningful unit of your program. When you hand your code over to
the C compiler, the very first thing it does is strip away all your spaces, blank lines, and
comments, and chops the remaining text up into these tiny tokens.
Easy2Siksha.com
Tokens come in six different flavors:
Keywords: These are reserved, special words that already have a specific meaning to
the C compiler. You cannot use these for anything else. Words like int, return, if, and
while are keywords. Think of them as the standard verbs of the C language.
Identifiers: These are the names you invent. When you create a variable to hold the
user's score, and you name it playerScore, that name is an identifier.
Constants: These are fixed numeric or character values that do not change, like the
number 42 or 3.14.
Strings: Any text wrapped in double-quotes, like "Hello, World!".
Special Symbols: The punctuation marks of C code. This includes brackets [ ], braces
{ }, commas ,, and semicolons ;.
Operators: Symbols that perform mathematical or logical operations, such as +, -, =,
or ==.
Let’s look at a very simple line of code: int age = 20;
To you, this is one instruction. But to the compiler, it is a sequence of exactly five distinct
tokens:
1. int (Keyword)
2. age (Identifier)
3. = (Operator)
4. 20 (Constant)
5. ; (Special Symbol)
Understanding tokens is crucial because when you get a "Syntax Error," it usually means you
put a token in the wrong place, or you forgot one entirely (like that notoriously elusive
semicolon!).
2. #define: The Magical Copy-Paste Machine
Now that we have our basic building blocks, let's talk about a tool that saves you from
endless repetition.
Have you ever written a long essay in a word processor and realized you misspelled a main
character’s name fifty times? What do you do? You don't read through the whole document
to fix them one by one. You use the "Find and Replace" tool.
In C, #define (pronounced "hash define") is your automated Find-and-Replace tool. It is part
of something called the preprocessor, which is a program that runs before the actual
compiler even looks at your code.
We use #define to create macros or symbolic constants.
Let's say you are writing a program to calculate the area of various circles. You will need to
use the value of Pi repeatedly. You could just type 3.14159 every single time you need it. But
what if, halfway through your massive project, your boss tells you that your calculations
Easy2Siksha.com
need to be more precise, and you must now use 3.14159265? You would have to hunt down
every single instance of the old number and change it. If you miss even one, your program
will have a bug.
Instead, at the very top of your file, you write: #define PI 3.14159
Now, anywhere in your code, you can just type the word PI. area = PI * radius * radius;
When you click "compile," the preprocessor sweeps through your code. Everywhere it sees
the token PI, it physically deletes it and pastes 3.14159 in its place, right before handing the
code off to the compiler. The compiler never actually sees the word PI; it only sees the
numbers.
This makes your code incredibly readable. It also means if you ever need to change the
value, you only change it in one single place at the top of your file, and the preprocessor
automatically updates it everywhere else.
3. typedef: The Master of Nicknames
While #define is a text-replacement tool used by the preprocessor, typedef is a tool
completely owned by the compiler itself. typedef allows you to give a new namea
nickname or aliasto an existing data type.
Why would you want to do this? Let's use an analogy. Imagine you work in a mechanic's
shop, and there is a tool officially called the "Pneumatic Rotational Fastening Device." It’s a
mouthful. Every time you need it, saying the whole name is exhausting. So, everyone in the
shop just agrees to call it the "Impact Gun." You haven't invented a new tool; you've just
given an existing, complicated tool a much friendlier nickname.
In C, you often deal with data types that are frustratingly long to type. For example, if you
want to store a very large positive number, you have to use the data type unsigned long
long int. Typing that out over and over again is tedious and makes your code look cluttered.
Instead, you can use typedef: typedef unsigned long long int BigNumber;
From that moment on, the compiler knows that BigNumber means the exact same thing
as unsigned long long int. You can now declare variables simply like this: BigNumber
distanceToSun; BigNumber nationalDebt;
Another massive benefit of typedef is portability. Different computer systems sometimes
handle data types differently. If you write a huge program using typedef nicknames for all
your integers, and later you move your program to a completely different type of computer
processor, you only have to change your typedef definitions at the top of the file. You don't
have to rewrite the entire program!
4. enum: The Drop-Down Menu of Choices
Finally, let's look at enum, which is short for enumeration.
Easy2Siksha.com
Imagine you are filling out an online form. When it asks for your State or Province, does it
give you an empty text box to type whatever you want? Usually, no. If they let people type
anything, someone might misspell "California" as "Kalifornia," or just type "Pizza" as their
state. To prevent this chaos, the form gives you a drop-down menu with a strict, limited list
of valid choices.
An enum is the programmer's way of creating a drop-down menu of restricted choices in
code. It is a user-defined data type where you explicitly list out all the possible values that a
variable of this type can hold.
Let’s say you are writing a program to control a traffic light. The light can only be three
colors: Red, Yellow, or Green.
If you just use standard integers to represent these (e.g., 1 for Red, 2 for Yellow, 3 for
Green), your code can get confusing very quickly. Six months from now, you might look at
the line if (lightState == 2) and completely forget what 2 was supposed to mean. Worse,
what if someone accidentally sets the light to 99? The program wouldn't know what to do!
Instead, you create an enum: enum TrafficLight { RED, YELLOW, GREEN };
Now you can create a variable specifically of this type: enum TrafficLight currentLight = RED;
Later in your code, you can write highly readable logic: if (currentLight == GREEN)
{ driveForward(); }
Under the hood, C is actually incredibly lazy. It doesn't really store the words "RED" or
"GREEN". The compiler secretly assigns the integer 0 to RED, 1 to YELLOW, and 2 to GREEN.
But as the programmer, you never have to worry about those numbers. You get to use the
descriptive English words, making your code self-documenting and much easier for other
humans to read and understand.
Bringing It All Together
When you write software, you are essentially writing an incredibly detailed instruction
manual for a machine that has absolutely no common sense.
To write this manual well, you break your thoughts down into the precise vocabulary of
Tokens. You use #define to create sweeping blueprints that save you from repetitive typing
and hidden bugs. You use typedef to create friendly nicknames for complex data, keeping
your manual clean and easy to read. And you use enum to establish strict, readable lists of
choices so that the computer (and other programmers) don't get confused by random
numbers.
Easy2Siksha.com
SECTION-B
3. Write a program in C to get a number from the user and calculate the sum of all its
digits which are even.
Ans: Understanding the Question
Suppose the user enters a number:
248631
Now look carefully at each digit:
Digit
Even or Odd
2
Even
4
Even
8
Even
6
Even
3
Odd
1
Odd
We only need to add the even digits.
So:
2 + 4 + 8 + 6 = 20
Therefore, the output will be:
Sum of even digits = 20
What Concepts Are Asked in This Question?
This small question actually checks many programming concepts together.
The concepts are:
1. Input from user
2. Loops
3. Digits extraction
4. Even number checking
5. Addition using variable
6. Basic logic building
Let us understand each one slowly.
Easy2Siksha.com
1. Taking Input from User
In C programming, we use:
scanf()
to take input from the user.
Example:
scanf("%d", &num);
Here:
%d means integer value
&num means address of variable
Suppose user enters:
248631
Now this value gets stored in variable num.
2. What Are Digits?
A number is made of digits.
Example:
248631
contains:
2, 4, 8, 6, 3, 1
But the computer sees the whole number together.
So we need a method to separate digits one by one.
3. How Do We Extract Digits?
This is the most important concept.
We use:
Easy2Siksha.com
num % 10
This gives the last digit of the number.
Example:
248631 % 10 = 1
So last digit is 1.
Diagram of Digit Extraction
248631
|
| %10
1 ← Last Digit
After getting the last digit, we remove it using:
num = num / 10;
Now:
248631 / 10 = 24863
The last digit is removed.
Full Process Diagram
Step 1:
Number = 248631
Digit = 1
Step 2:
Number = 24863
Digit = 3
Step 3:
Number = 2486
Digit = 6
Step 4:
Number = 248
Digit = 8
Easy2Siksha.com
Step 5:
Number = 24
Digit = 4
Step 6:
Number = 2
Digit = 2
This process continues until the number becomes 0.
4. How to Check Even Digits?
An even number is divisible by 2.
Examples:
2, 4, 6, 8
We check even numbers using:
digit % 2 == 0
If condition becomes true, then digit is even.
Example:
6 % 2 = 0
So 6 is even.
5. Sum Variable
We need a variable to store addition.
Example:
sum = sum + digit;
Initially:
sum = 0
Then:
Easy2Siksha.com
sum = 0 + 2 = 2
sum = 2 + 4 = 6
sum = 6 + 8 = 14
sum = 14 + 6 = 20
Final answer becomes:
20
6. Why Do We Need Loop?
Because digits are many.
We cannot write separate code for every digit.
So we use a loop.
Mostly:
while(num > 0)
This loop runs until all digits are processed.
Complete Logic in Simple English
Let us understand the entire logic like a story.
Suppose your number is:
248631
The computer says:
󷷑󷷒󷷓󷷔 “I will pick one digit at a time from the end.”
First digit:
1
Is it even?
󽆱 No
Ignore it.
Easy2Siksha.com
Next digit:
3
Even?
󽆱 No
Ignore.
Next digit:
6
Even?
󷄧󼿒 Yes
Add it.
Then:
8
󷄧󼿒 Add
Then:
4
󷄧󼿒 Add
Then:
2
󷄧󼿒 Add
Finally:
20
C Program
#include <stdio.h>
int main()
Easy2Siksha.com
{
int num, digit, sum = 0;
printf("Enter a number: ");
scanf("%d", &num);
while(num > 0)
{
digit = num % 10;
if(digit % 2 == 0)
{
sum = sum + digit;
}
num = num / 10;
}
printf("Sum of even digits = %d", sum);
return 0;
}
Dry Run of Program
Suppose input is:
248631
Number
Digit
Even?
Sum
248631
1
No
0
24863
3
No
0
2486
6
Yes
6
248
8
Yes
14
24
4
Yes
18
2
2
Yes
20
Final Output:
Sum of even digits = 20
Important Points to Remember
% Operator
Used to get remainder.
num % 10
Easy2Siksha.com
gives last digit.
/ Operator
Used to remove last digit.
num / 10
Even Number Formula
digit % 2 == 0
Loop Condition
while(num > 0)
Runs until number becomes zero.
Real Life Analogy
Imagine you have a box of numbered balls:
2 4 8 6 3 1
You pick one ball at a time.
If the number is even:
󷄧󼿒 Put it into the “addition basket”.
If odd:
󽆱 Ignore it.
At the end, add all numbers in the basket.
That is exactly what this program does.
Conclusion
Easy2Siksha.com
This question teaches one of the most important concepts in C programming: digit
manipulation.
By solving this problem, students learn:
How loops work
How digits are separated
How conditions work
How arithmetic operators are used
How logic is built in programming
Although the question looks difficult at first, the idea is actually very simple:
4. What is a storage class? Explain different storage classes available in C. Give an example
of each.
Ans: Have you ever wondered how a C program keeps track of all its variables? When you
write a simple line of code like int score = 100;, you might just think of it as a labeled box
inside your computer holding a number. But there is a secret manager working behind the
scenes to control exactly how that box behaves. In the C programming language, this
manager is called a storage class.
To understand this complex topic, let's step away from the computer screen for a moment.
Imagine that your C program is not a piece of software, but a bustling, high-end restaurant.
In this restaurant, information (your variables) is constantly moving around. Sometimes you
need a temporary plate of food for one specific customer. Other times, you need a master
recipe book that every chef in the kitchen can read. A storage class is simply the set of rules
that tells the restaurant staff how to handle a specific piece of information.
Whenever you create a variable in C, its storage class defines four crucial pillars of its
existence:
1. Storage Location: Where is the variable physically kept? Is it in the standard, roomy
kitchen pantry (RAM), or right in the chef's hands for lightning-fast access (CPU
Registers)?
2. Default Initial Value: If you create a variable but forget to give it a starting value,
what happens? Does it start perfectly clean at 0, or is it filled with random "garbage"
left over from the last customer?
3. Scope (Visibility): Who is allowed to see and use this variable? Is it restricted to just
one table (a single function), or can the entire restaurant (the whole program) access
it?
4. Lifetime: How long does this variable exist before it is thrown in the trash to make
room for new things?
Easy2Siksha.com
C provides four distinct storage classes to handle every possible scenario: Automatic,
Register, Static, and External. Let’s walk through the restaurant and meet each one.
1. The auto Storage Class: The Customer's Plate
The Metaphor:
Imagine a waiter brings a plate of spaghetti to Table 5. That plate belongs only to Table 5 (its
scope). As soon as the customer finishes eating and leaves, the waiter clears the plate away
and washes it (its lifetime ends). If you look at a dirty plate before it's washed, it might have
random leftover scraps on it (garbage value).
The Concept:
The auto (automatic) storage class is the default setting for all local variables. If you declare
a variable inside a function and don't specify a storage class, the compiler automatically
makes it auto.
Location: RAM (Main Memory)
Default Value: Garbage value (unpredictable random numbers)
Scope: Local (only visible inside the block or function where it was created)
Lifetime: Ends the moment the function finishes executing.
The Code Example:
#include <stdio.h>
void serveCustomer() {
// We can explicitly write 'auto', but it is completely
optional.
auto int platesServed = 1;
// This variable has no initial value, so it holds
"garbage" data.
int leftoverScraps;
printf("Plates served: %d\n", platesServed);
printf("Leftovers (Garbage): %d\n", leftoverScraps);
}
int main() {
serveCustomer();
// If we try to print platesServed here, the program will
crash!
// The variable was destroyed when serveCustomer()
finished.
return 0;
}
Easy2Siksha.com
When you run this, platesServed prints exactly as 1, but leftoverScraps will print a totally
random, bizarre number (like 32767 or -8573) because we never initialized it.
2. The register Storage Class: The Chef’s Pocket
The Metaphor:
The head chef is busy chopping vegetables. If he keeps walking all the way across the
kitchen to the main pantry (RAM) to grab one carrot at a time, service will slow to a crawl.
Instead, he keeps his most frequently used knife right in his apron pocket. It’s incredibly fast
to reach, but his pocket has very limited space.
The Concept:
The register storage class is a polite request to the computer’s compiler. You are asking,
"Hey, I am going to use this variable thousands of times in the next few milliseconds. Please
don't put it in the normal RAM. Put it directly into the CPU's internal registers so I can access
it at lightning speed."
Location: CPU Register (if available)
Default Value: Garbage value
Scope: Local to the function
Lifetime: Ends when the function finishes.
Note: Modern compilers are so smart that they usually decide for themselves what goes into
a register, even if you don't use this keyword. But it remains an important historical concept.
The Code Example:
#include <stdio.h>
void chopVegetables() {
// We request this loop counter to be stored in the ultra-
fast CPU register
register int i;
// A rapid loop where speed is essential
for(i = 1; i <= 3; i++) {
printf("Chopped vegetable %d\n", i);
}
}
int main() {
chopVegetables();
return 0;
}
You won't visually see a difference in the output, but under the hood, the computer tries to
execute this specific loop faster by keeping the variable i right next to the processor's brain.
Easy2Siksha.com
3. The static Storage Class: The Daily Tip Jar
The Metaphor:
At the front counter, there is a glass tip jar. When the morning cashier goes on a lunch break
(the function ends), the tip jar doesn't get thrown in the trash. The money stays right there.
When the afternoon cashier arrives (the function is called again), they continue adding
money to the exact same jar. The jar remembers its history for the entire day. Also, when
the restaurant opens in the morning, the jar is always perfectly empty (initialized to zero).
The Concept:
The static storage class is pure magic. It tells a local variable to remember its value even
after the function that created it has finished running. The next time you call that function,
the static variable will pick up exactly where it left off.
Location: RAM
Default Value: 0 (clean and empty, no garbage here!)
Scope: Local to the function
Lifetime: The entire duration of the program (it survives until the program
completely closes).
The Code Example:
#include <stdio.h>
void addTip() {
// This variable is created only ONCE.
// It remembers its value between function calls.
static int tipJar = 0;
// This is a normal auto variable. It gets destroyed and
recreated every time.
int pocketChange = 0;
tipJar += 5;
pocketChange += 5;
printf("Tip Jar has: $%d | Pocket has: $%d\n", tipJar,
pocketChange);
}
int main() {
printf("Customer 1 leaves a tip:\n");
addTip(); // Tip Jar: 5, Pocket: 5
printf("Customer 2 leaves a tip:\n");
addTip(); // Tip Jar: 10, Pocket: 5
Easy2Siksha.com
printf("Customer 3 leaves a tip:\n");
addTip(); // Tip Jar: 15, Pocket: 5
return 0;
}
Notice the difference! The pocketChange variable suffers from amnesia; it forgets
everything and resets to 5 every single time. But the tipJar remembers. It grows to 5, then
10, then 15.
4. The extern Storage Class: The Giant Neon Sign
The Metaphor:
Outside the restaurant, there is a massive neon sign flashing the words "NOW OPEN." This
sign isn't hidden in the kitchen or restricted to one table. Anyone, anywhere, standing in any
part of the town (any file in your program) can look up, see the sign, and know the
restaurant's status.
The Concept:
As your C programs get larger, you will start splitting your code into multiple different .c
files. The extern (external) storage class allows you to declare a global variable in one file,
and then share it across many other files. You are telling the compiler, "I am using a variable
here, but don't create a new one! Go look outside; it has already been defined somewhere
else."
Location: RAM
Default Value: 0
Scope: Global (visible to all files in the program)
Lifetime: The entire duration of the program.
The Code Example:
Imagine you have two separate files making up your program.
File 1: kitchen.c
#include <stdio.h>
// We define the global variable here.
// Because it's global, it naturally defaults to 0.
int totalPizzasBaked = 50;
File 2: main.c
#include <stdio.h>
// We use 'extern' to tell the compiler:
// "Go find totalPizzasBaked! It exists in another file."
Easy2Siksha.com
extern int totalPizzasBaked;
int main() {
printf("The neon sign says we have baked %d pizzas
today!\n", totalPizzasBaked);
// We can even change it, and it affects the master copy!
totalPizzasBaked += 10;
printf("Update! Now we have baked %d pizzas!\n",
totalPizzasBaked);
return 0;
}
When main.c runs, it perfectly links up with the variable hiding in kitchen.c. They share the
exact same piece of memory.
The Master Cheat Sheet
To wrap up our tour of the C programming kitchen, here is a quick reference table
summarizing everything we’ve learned. Keep this in mind, and you will never be confused by
storage classes again!
Storage
Class
Default Initial
Value
Scope (Who
can see it?)
Lifetime (How long does
it live?)
auto
Garbage Value
Local (Within a
block)
Ends when the
block/function ends
register
Garbage Value
Local (Within a
block)
Ends when the
block/function ends
static
Zero (0)
Local (Within a
block)
Lives until the whole
program ends
extern
Zero (0)
Global (Across
all files)
Lives until the whole pr
SECTION-C
5. What are the different ways to pass arguments to a function in C? Give an example of
each.
Ans: What are the different ways to pass arguments to a function in C?
In C language, there are mainly two ways to pass arguments to a function:
1. Call by Value
2. Call by Reference
Understanding Functions First
Easy2Siksha.com
Imagine you own a restaurant.
The customer gives an order to the chef:
“Make 2 burgers.”
Here:
Customer = Main function
Chef = Called function
Order details = Arguments
The chef needs some information to prepare food. Similarly, a function needs data to
perform work.
General Syntax of a Function
return_type function_name(parameters)
{
// code
}
Example:
int add(int a, int b)
{
return a + b;
}
Here:
a and b are arguments/parameters.
Two Ways of Passing Arguments
1. Call by Value
In this method, a copy of the original value is passed to the function.
This means:
The function works on duplicate data.
Original variables remain unchanged.
Easy2Siksha.com
Real Life Example of Call by Value
Suppose your friend asks for your notebook photocopy.
You give him a photocopy, not the original notebook.
Now:
If your friend writes something on the photocopy,
Your original notebook stays safe.
This is exactly how Call by Value works.
Diagram of Call by Value
Main Function
x = 10
|
| sends COPY
v
Function receives 10
Function changes value to 20
Original x still = 10
Example Program of Call by Value
#include <stdio.h>
void change(int num)
{
num = 50;
printf("Value inside function: %d\n", num);
}
int main()
{
int x = 10;
printf("Before function call: %d\n", x);
change(x);
printf("After function call: %d\n", x);
Easy2Siksha.com
return 0;
}
Output
Before function call: 10
Value inside function: 50
After function call: 10
Explanation
Step-by-step understanding:
Step 1:
Variable x is created in main().
x = 10
Step 2:
Function call happens.
change(x);
Here, only a copy of x is sent.
Step 3:
Inside the function:
num = 50;
Only copied value changes.
Step 4:
Original x remains unchanged.
That is why output is still:
After function call: 10
Important Features of Call by Value
Easy2Siksha.com
Feature
Explanation
Copy is passed
Original data stays safe
Changes not reflected
Function cannot modify original variable
Memory safe
Less risky
Simple to use
Easy for beginners
When is Call by Value Used?
It is used when:
We do not want to change original data.
Only calculation or temporary work is needed.
Example:
Addition
Multiplication
Finding square
2. Call by Reference
In this method, the address of the variable is passed to the function.
This means:
Function directly accesses original data.
Changes inside function affect original variables.
In C, Call by Reference is achieved using pointers.
Real Life Example of Call by Reference
Imagine you give your friend your original notebook instead of photocopy.
Now:
Whatever your friend writes,
Changes happen in the original notebook itself.
This is Call by Reference.
Easy2Siksha.com
Diagram of Call by Reference
Main Function
x = 10
Address = 1000
|
| sends ADDRESS
v
Function accesses original x
Function changes x to 50
Original x becomes 50
Example Program of Call by Reference
#include <stdio.h>
void change(int *num)
{
*num = 50;
printf("Value inside function: %d\n", *num);
}
int main()
{
int x = 10;
printf("Before function call: %d\n", x);
change(&x);
printf("After function call: %d\n", x);
return 0;
}
Output
Before function call: 10
Value inside function: 50
After function call: 50
Understanding This Program Carefully
This program may look difficult at first, but it is actually simple.
Easy2Siksha.com
Step 1: Variable Creation
int x = 10;
Suppose:
Value = 10
Address = 1000
Step 2: Sending Address
change(&x);
&x means:
“Send the address of x.”
Step 3: Receiving Address
void change(int *num)
*num means:
Pointer variable
It stores address
So:
num stores 1000
Step 4: Modifying Original Value
*num = 50;
This means:
Go to address 1000
Change value to 50
Now original x becomes 50.
Easy2Siksha.com
Easy Understanding of Symbols
Symbol
Meaning
&
Address of variable
*
Value stored at address
Pointer
Variable storing address
Comparison Between Call by Value and Call by Reference
Call by Value vs Call by Reference
Comparison of how data behaves in both argument passing methods.
0%25%50%75%100% Call by ValueCall by Reference
Basis
Call by Value
Call by Reference
What is passed?
Copy of value
Address of variable
Original value changes?
No
Yes
Memory use
More copies created
Efficient
Safety
More secure
Risk of accidental changes
Uses pointers?
No
Yes
Why Do We Need Call by Reference?
Sometimes we need a function to:
Swap numbers
Update values
Modify arrays
Save memory
In such cases, Call by Reference is very useful.
Example: Swapping Two Numbers
This is a famous use of Call by Reference.
#include <stdio.h>
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
Easy2Siksha.com
*b = temp;
}
int main()
{
int x = 5, y = 10;
printf("Before swap: %d %d\n", x, y);
swap(&x, &y);
printf("After swap: %d %d\n", x, y);
return 0;
}
Output
Before swap: 5 10
After swap: 10 5
Without Call by Reference, swapping original variables would not be possible easily.
Final Conclusion
Passing arguments to functions is a very important concept in C programming because
functions need data to perform tasks.
There are mainly two methods:
1. Call by Value
Sends copy of data
Original value remains unchanged
Safer and simple
2. Call by Reference
Sends address of variable
Original value changes
Uses pointers
Easy2Siksha.com
6. What is a pointer? What are the various uses of pointers?
Give an example of passing an array to a function.
Ans: Let’s take a journey into the heart of how your computer actually thinks and organizes
its world. For many students learning programming, particularly in languages like C or C++,
the concept of "pointers" is often treated like a monster hiding under the bed. It has a
reputation for being abstract, confusing, and prone to causing your programs to crash.
But I promise you, once you understand the simple, elegant logic behind them, pointers
become less like a monster and more like a superpower. They grant you direct control over
the very fabric of your computer. To understand pointers, we first need to take a step back
and understand the world they live in: the computer's memory.
The City of Memory
Imagine your computer's RAM (Random Access Memory) as a massive, sprawling city. This
city is made up of millions and millions of tiny, identical houses, lined up neatly row after
row along endless streets. Each of these houses represents a single "byte" of memory, and
just like houses in the real world, every single one of them has a unique street address. We
usually write these addresses in computer code using a format called hexadecimal (which
looks something like 0x7FFE), but for our story, let's just imagine they are numbered
sequentially from 1 to a billion.
When you write a program and create a standard variablelet's say, you type int age =
20;you are essentially asking the city planner (the operating system) to do you a favor.
You are asking it to find an empty house, paint the name age on the mailbox, and put the
number 20 inside it. From then on, if you want to know the person's age, you just type age,
and the computer dutifully runs over to that specific house, opens the door, and fetches the
data for you.
So, What Exactly is a Pointer?
But what if, instead of holding a piece of data like a number, a letter, or a name, a variable
held an address?
That is exactly what a pointer is. A pointer is simply a special type of variable that stores
the memory address of another variable. It doesn't hold the treasure; it holds the map to
the treasure. If I give you a piece of paper that says "123 Main Street," the paper itself isn't a
house, and you can't live inside it. But that paper points you directly to where the house is
located. In programming, a regular variable holds the actual data, while a pointer holds the
location of that data.
The Big Question: Why Do We Even Need Pointers?
At this point, it is perfectly natural to ask: "If I already have the variable with the data inside
it, why on earth would I want to play a game of hide-and-seek using addresses?" It comes
down to efficiency, speed, and unlocking capabilities that normal variables simply cannot
Easy2Siksha.com
handle. Here are the primary uses of pointers that make them the secret engine of powerful
programming:
1. Avoiding the "Heavy Lifting" (Pass by Reference)
Imagine you have written a massive, 1,000-page encyclopedia inside your program, and you
want a specific function to analyze it for spelling errors. If you pass that variable to the
function normally (a concept called "pass by value"), the computer literally has to
photocopy all 1,000 pages and hand the massive stack of copies to the function. This wastes
an enormous amount of time and computer memory.
With a pointer, you completely bypass this heavy lifting. You simply hand the function a
little index card with the address of the encyclopedia. You are telling the function, "I'm not
copying the book for you. The data you need is over at this location; go look at it yourself."
This is lightning-fast and uses almost zero extra memory.
2. Dynamic Memory Allocation (Renting Rooms on the Fly)
When you write a standard program, you usually have to declare exactly how much memory
you need before the program runs. But what if you are building an app, and you don't know
how many photos a user is going to upload until they actually start clicking buttons?
Pointers allow you to ask the computer for new memory while the program is running. It's
like running a hotel where you can magically build new rooms the moment a guest arrives.
The computer finds an empty block of houses, builds the rooms, and gives you the pointers
(the addresses) to those new rooms so you can keep track of where you put your new data.
3. Building Complex Data Structures
Think of a classic scavenger hunt, where Clue #1 tells you exactly where to find Clue #2, and
Clue #2 points you to Clue #3. In computer science, we build incredibly powerful, flexible
structures like "Linked Lists" and "Trees" using this exact logic. Every piece of data contains a
pointer connecting it to the next piece of data. This allows you to chain massive webs of
information together across the city of memory.
4. Direct Hardware Access
When you write software that physically interacts with a machinelike a digital
thermometer, a robotic arm, or a computer's graphics cardthose physical hardware
components often listen for instructions at very specific, hardcoded memory addresses.
Pointers give you the ability to reach out and write commands directly to that exact physical
spot in the machine's brain.
The Array Connection: Passing an Array to a Function
Now, let's tie this all together with the final part of your question: arrays. Pointers and
arrays are deeply, inextricably linked.
Easy2Siksha.com
Imagine an array not as a single house, but as a row of identical townhouses built right next
to each other on the exact same street. If you create an array of five test scores, the
computer finds five empty houses sitting side-by-side and puts a score in each one.
Here is the ultimate secret of C and C++ programming: the name of the array is secretly just
a pointer to the very first element. The computer is smart. It knows that since these
townhouses are perfectly identical and built sequentially, it doesn't need to memorize the
address of every single house. If it knows where the first house is, it can easily find the
second, third, and fourth just by walking down the street.
Because of this, when you want to pass an array into a function, you don't pick up the entire
street of townhouses and hand it to the function. You just give the function the address of
the very first house.
Here is what that looks like in action:
#include <stdio.h>
// This function calculates the sum of all numbers in an
array.
// Notice the parameter: int *arr. It is expecting a POINTER
to an integer!
void calculateSum(int *arr, int size) {
int total = 0;
// We use a loop to walk down the "street" of memory
for (int i = 0; i < size; i++) {
// arr[i] tells the computer: start at the address
'arr',
// and walk 'i' houses down the street to get the
data.
total = total + arr[i];
}
printf("The total sum is: %d\n", total);
}
int main() {
// We build our row of 5 townhouses
int myScores[5] = {10, 20, 30, 40, 50};
// We pass 'myScores' to the function.
// Remember, 'myScores' is secretly just the address of
the '10'!
calculateSum(myScores, 5);
return 0;
}
Breaking Down the Code Story:
Easy2Siksha.com
1. In main(), we create myScores. The computer finds five adjacent memory blocks and
stores 10, 20, 30, 40, 50. Let's say the first block is at address 100.
2. We call calculateSum(myScores, 5). We are passing the number 100 (the address)
and the number 5 (how many houses are on the block).
3. Up in the calculateSum function, the pointer int *arr catches that address. arr now
knows to look at address 100.
4. As the loop runs, arr[0] looks at the house at address 100. arr[1] takes a step next
door to address 104 (integers take up 4 bytes of space usually). arr[2] steps next
door again.
By passing just that single starting address, the function was able to access and read the
entire array without having to make a copy of a single number.
Pointers might seem daunting at first glance because they force you to think about where
things are rather than just what they are. But once you start picturing that city of memory,
and seeing pointers simply as the addresses and treasure maps guiding you through the
streets, the whole concept clicks into place.
SECTION-D
7 What are user-defined data types in C? How can you create a structure and union in C? Give
differences between both.
Ans: User-Defined Data Types in C Structure and Union
In the C programming language, data is very important. Every program works with data such
as numbers, names, marks, addresses, and many other types of information. C already
provides some basic data types like int, float, char, and double. These are called built-in
data types.
But sometimes, a programmer needs to store different kinds of related information
together. For example, if we want to store information about a student, we may need:
Student name
Roll number
Marks
Age
Using separate variables for each student becomes confusing and difficult to manage. To
solve this problem, C provides user-defined data types.
What are User-Defined Data Types in C?
Easy2Siksha.com
User-defined data types are data types created by the programmer according to the needs
of the program.
They allow the programmer to combine different types of data and create a new customized
data type.
C provides the following user-defined data types:
1. Structure (struct)
2. Union (union)
3. Enumeration (enum)
4. Typedef (typedef)
Among these, Structure and Union are very important and commonly used.
Structure in C
A structure is a user-defined data type that allows us to store different types of related data
under one name.
It is like a container that keeps related information together.
Real-Life Example of Structure
Think about a student identity card.
It contains:
Name
Roll Number
Class
Phone Number
All these details belong to one student.
Similarly, a structure groups related data together.
Syntax of Structure
struct Student
{
int roll;
char name[20];
Easy2Siksha.com
float marks;
};
Here:
Student is the structure name.
roll, name, and marks are structure members.
Creating Structure Variables
struct Student s1;
Now s1 can store one student’s information.
Accessing Structure Members
We use the dot operator (.)
Example:
s1.roll = 101;
s1.marks = 85.5;
Complete Example of Structure
#include<stdio.h>
struct Student
{
int roll;
char name[20];
float marks;
};
int main()
{
struct Student s1;
s1.roll = 1;
s1.marks = 92.5;
printf("Roll Number = %d\n", s1.roll);
printf("Marks = %.2f", s1.marks);
Easy2Siksha.com
return 0;
}
Diagram of Structure
Structure: Student
+-------------------+
| Roll Number |
+-------------------+
| Name |
+-------------------+
| Marks |
+-------------------+
Each member gets its own separate memory location.
Important Features of Structure
1. Stores Different Types of Data
A structure can contain:
Integer
Character
Float
Array
all together.
2. Each Member Has Separate Memory
Every member occupies its own memory space.
For example:
struct Test
{
int a;
float b;
char c;
};
Easy2Siksha.com
Memory is allocated separately for a, b, and c.
3. Used for Complex Data
Structures are widely used in:
Student records
Employee management
Library systems
Banking software
Union in C
A union is also a user-defined data type that groups different data types together.
But there is one major difference:
In a union, all members share the same memory location.
This means only one member can store a value at a time.
Real-Life Example of Union
Imagine a single parking space.
At one time:
Either a bike can park
Or a car can park
Both cannot use the same space together.
Similarly, in a union, members share one memory area.
Syntax of Union
union Data
{
int i;
float f;
Easy2Siksha.com
char str[20];
};
Creating Union Variables
union Data d1;
Accessing Union Members
d1.i = 10;
Complete Example of Union
#include<stdio.h>
union Data
{
int i;
float f;
};
int main()
{
union Data d1;
d1.i = 10;
printf("Integer = %d\n", d1.i);
d1.f = 5.5;
printf("Float = %.1f\n", d1.f);
return 0;
}
Diagram of Union
Union: Data
Shared Memory
+-------------------+
| int i |
| float f |
| char str[20] |
+-------------------+
Easy2Siksha.com
All members use the same memory space.
How Union Memory Works
Suppose:
int needs 4 bytes
float needs 4 bytes
char str[20] needs 20 bytes
Then the union size will be:
20 bytes
because the largest member determines the memory size.
Structure vs Union
The biggest confusion for students is understanding the difference between structure and
union.
Let us understand it simply.
Differences Between Structure and Union
Basis
Structure
Union
Memory
Allocation
Separate memory for each member
Shared memory for all members
Data Storage
All members can store values
simultaneously
Only one member stores value
at a time
Memory Usage
More memory
Less memory
Keyword Used
struct
union
Access
All members accessible together
Latest assigned value remains
valid
Size
Sum of all member sizes
Size of largest member
Usage
Complex records
Memory-saving applications
Simple Memory Comparison Diagram
Structure Memory
Easy2Siksha.com
+-----+-----+-----+
| a | b | c |
+-----+-----+-----+
Separate memory
Union Memory
+-----------------+
| a / b / c |
+-----------------+
Shared memory
When Should We Use Structure?
Use structures when:
All data members are needed together.
We want to store complete records.
Memory saving is not the main concern.
Example:
Student information
Employee records
Hospital databases
When Should We Use Union?
Use unions when:
Only one value is needed at a time.
Memory saving is important.
Different data types share the same memory.
Example:
Embedded systems
Hardware programming
Memory optimization programs
Conclusion
Easy2Siksha.com
User-defined data types in C help programmers create customized data structures according
to program requirements. Among them, Structure and Union are very important.
A Structure stores different types of related data with separate memory allocation for each
member. It is useful for storing complete records like student or employee details.
A Union, on the other hand, shares the same memory among all members. It saves memory
but allows only one member’s value to exist at a time.
In simple words:
Structure = Separate rooms for everyone
Union = One room shared by everyone
Both are extremely useful in C programming, and understanding their differences helps
students write efficient and organized programs.
8 Write and explain various file handling functions available in C.
Ans: Imagine playing a video game for hours, building an epic city or leveling up your
character, only to accidentally unplug the console before hitting "Save." Devastating, right?
That is exactly what happens to the data inside a standard C program. Whenever you create
a variable or an array, that information lives in the computer’s RAM (Random Access
Memory), which is strictly temporary. The moment your program finishes running, poofall
your hard work vanishes.
File handling in C is your "Save Game" feature. It allows your program to reach out of its
temporary memory space and permanently write data to a file on your hard drive (like a .txt
or .dat file), or read data that was saved previously.
To understand how this works, let's think of a file on your computer as a physical notebook
locked inside a filing cabinet. Your C program is a person sitting at a desk, trying to read or
write in that notebook. Let's walk through the toolsthe functionsyour program needs to
accomplish this.
1. The Bridge: FILE *
Before we look at the functions, we need a way to hold the notebook. In C, we use a special
tool called a File Pointer, written as FILE *. Think of this pointer as a robotic arm. Your
program uses this arm to grab the file, keep its place on the page, and pass data back and
forth. Every file handling function requires this pointer.
2. Opening the Notebook: fopen()
Easy2Siksha.com
You cannot read or write in a notebook while it is closed. The fopen() function is how you
unlock the cabinet, pull out the notebook, and open it.
When you use fopen(), you have to tell the computer how you want to use the file by
providing a "mode."
"r" (Read): You are just reading. If the file doesn't exist, the computer gives you an
error.
"w" (Write): You want to write. Warning: If the file already exists, this mode erases
everything in it and gives you a blank page! If it doesn't exist, it creates a new one.
"a" (Append): You want to add to the end of the file. It opens the notebook and
safely flips to the very last page so you don't erase any past work.
3. Writing in the Notebook (Output Functions)
Once the notebook is open in "w" or "a" mode, you need a pen. C gives you a few different
pens depending on what you want to write:
fputc() (File Put Character): This is for writing a single letter or symbol at a time. It's
like carefully writing one letter: A.
fputs() (File Put String): This writes a whole sentence or paragraph (a string) into the
file at once. It's much faster than writing letter by letter.
fprintf() (File Print Formatted): You probably already know printf(), which prints
beautifully formatted text with variables to your screen. fprintf() does the exact
same thing, but it prints that text directly into your file. It is the most powerful and
commonly used writing tool.
4. Reading the Notebook (Input Functions)
If you open the file in "r" mode, you need to read what’s inside and bring it back into your
program's variables. C gives you reading glasses of different strengths:
fgetc() (File Get Character): This reads the file slowly, character by character. It looks
at the first letter, passes it to your program, and moves its finger to the next letter.
When it hits the end of the notebook, it returns a special signal called EOF (End of
File).
fgets() (File Get String): This reads a whole line of text at a time until it hits a
"newline" (like an "Enter" key press) or reaches a maximum limit you set. It’s perfect
for reading lists or paragraphs.
fscanf() (File Scan Formatted): Just like scanf() reads formatted input from your
keyboard, fscanf() looks for specific patterns in the file. If you have a file filled with
"Name: Age" data, fscanf() can cleanly pull out the text into a word variable and the
age into a math variable.
5. Flipping the Pages (Navigation Functions)
Sometimes you don't want to read a file from the very beginning to the very end. You want
to jump around.
Easy2Siksha.com
fseek(): This tells the robotic arm to jump to a very specific spot in the file. It’s like
saying, "Skip the first 100 letters and start reading from there."
ftell(): If you get lost, this function tells you exactly where you are. It returns the
current position (in bytes) of your cursor in the file.
rewind(): Exactly what it sounds like! It snaps the robotic arm right back to the very
first letter on the very first page of the file.
6. Putting the Notebook Away: fclose()
This is the most critical step that beginners forget. When you are done writing or reading,
you must use fclose().
Why? Because computers are efficient. When you use fprintf(), the computer sometimes
holds onto your words in a temporary waiting room (a buffer) instead of writing them to the
hard drive immediately. fclose() forces the computer to write everything down
permanently, closes the notebook, puts the cap back on the pen, and safely returns the file
to the locked cabinet. If you don't use fclose(), you might lose the data you just tried to
save!
Putting it All Together
Here is a quick glimpse of how this looks in a real C program. It is a simple story of opening a
file, writing a sentence, and closing it safely:
#include <stdio.h>
int main() {
// 1. Create the robotic arm (File Pointer)
FILE *myFile;
// 2. Open the notebook in Write ("w") mode
myFile = fopen("diary.txt", "w");
if (myFile == NULL) {
printf("Error: Could not open the file!\n");
return 1;
}
// 3. Write a formatted sentence into the notebook
fprintf(myFile, "Day 1: I am learning C file handling. It
is actually quite logical!\n");
// 4. Put the notebook away safely
fclose(myFile);
printf("Data successfully saved to the hard drive.\n");
return 0;
}
Easy2Siksha.com
By mastering these simple toolspointers to hold the file, fopen to open it, fprintf and fgets
to communicate with it, and fclose to pack it awayyou give your programs the powerful
ability to remember things forever.
“This paper has been carefully prepared for educational purposes. If you notice any mistakes or
have suggestions, feel free to share your feedback.”